package com.mycompany.project.client.chee;
import com.mycompany.project.client.*;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.mycompany.project.client.Main;

/**
 * LoadSaveModuleDetailGUI class.
 * 
 * @author Chee Lee, Nick Neville
 * 
 */
@SuppressWarnings("deprecation")
public class LoadSaveModuleDetailGUI {

	/** private VerticalPanel veticalPanel. */
	private com.google.gwt.user.client.ui.VerticalPanel verticalPanel = new com.google.gwt.user.client.ui.VerticalPanel();

	/** private ListBox: listBox. */
	private ListBox listBox = new ListBox();

	/** private Button btnDeleteFile. */
	private Button btnDeleteFile = new Button("Delete File");

	/** private Button btnDeleteFile. */
	private Button btnLoadFile = new Button("Load File");

	/** private Button btnSaveFile. */
	private Button btnSaveFile = new Button("Save File");

	/** private TextBox textBox. */
	private TextBox textBox = new TextBox();

	/**
	 * private Integer: size = 0. keeps track of size of files
	 */
	private int size = 0;

	/**
	 * public LoadSaveModuleDetailGUI() method.
	 * 
	 * @function
	 * 
	 */
	public LoadSaveModuleDetailGUI() {

		verticalPanel.setSize("340px", "162px");

		HTML htmlSaveloadModuleDetails = new HTML("<center><b>Save/Load "
				+ "Logged Module Details</b></center>", true);

		verticalPanel.add(htmlSaveloadModuleDetails);
		HorizontalPanel horizontalPanel = new HorizontalPanel();
		verticalPanel.add(horizontalPanel);
		horizontalPanel.setSize("339px", "99px");

		com.google.gwt.user.client.ui.VerticalPanel vertPanel1 = new com.google.gwt.user.client.ui.VerticalPanel();

		vertPanel1.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		horizontalPanel.add(vertPanel1);
		HTML htmlfileName = new HTML("<center>File name:</center>", true);
		vertPanel1.add(htmlfileName);
		textBox.setAlignment(TextAlignment.CENTER);
		vertPanel1.add(textBox);
		textBox.setWidth("142px");
		textBox.setTitle("Enter new save file name");
		vertPanel1.add(btnSaveFile);
		btnSaveFile.setWidth("150px");
		vertPanel1.add(btnLoadFile);
		btnLoadFile.setWidth("150px");
		vertPanel1.add(btnDeleteFile);
		btnDeleteFile.setWidth("150px");

		com.google.gwt.user.client.ui.VerticalPanel verticalPanel2 = new com.google.gwt.user.client.ui.VerticalPanel();

		horizontalPanel.add(verticalPanel2);

		HTML htmlpreviousSavedFiles = new HTML(
				"<center>Previous saved file(s)</center>", true);
		verticalPanel2.add(htmlpreviousSavedFiles);

		verticalPanel2.add(listBox);
		listBox.setSize("125px", "95px");
		listBox.setVisibleItemCount(5);

		initAction();
		// end of load and save
	}

	/**
	 * private void initAction() method.
	 * 
	 * @function
	 * 
	 */
	private void initAction() {
		// If local storage has something in it and key item "save" is "yes"
		// then
		// we have previously saved files
		if (Main.getLocal().getLength() > 0
				&& Main.getLocal().getItem("Save") != null) {
			// Get the size of how many save files and store it into integer
			// size
			size = Integer.parseInt(Main.getLocal().getItem("Save Size"));
			// Find all available files
			for (int k = 0; k<size; k++) {
				if (Main.getLocal().getItem("SaveFile" + k) != null) {
					listBox.addItem(Main.getLocal().getItem("SaveFile" + k));
				}
			}
			// else no saved files exist.
		} else {
			size = 0;
		}
		// Save button function
		btnSaveFile.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(final ClickEvent event) {
				// first check if it has a unique file name
				for (int i = 0; i < listBox.getItemCount(); i++) {
					if (listBox.getItemText(i).equals(textBox.getText())) {
						Window.alert("Please select a unique file name!");
						return;
					}
				}
				if (textBox.getText().length() > 20) {
					Window.alert("Filename must be less than 19 characters.");
				} else if (textBox.getText().length() > 0
						&& textBox.getText().length() < 20) {
					// ask user first before updating
					final DialogBox popUp = new DialogBox(false);
					final VerticalPanel popPanel = new VerticalPanel();
					final HorizontalPanel hPanel = new HorizontalPanel();
					final Button noBtn = new Button("no");
					noBtn.setWidth("50px");
					final Button yesBtn = new Button("yes");
					yesBtn.setWidth("50px");
					popPanel.add(new HTML("<center>Save new file?</center>"));
					popPanel.add(hPanel);
					popUp.setWidget(popPanel);
					hPanel.add(yesBtn);
					hPanel.add(noBtn);
					popUp.setPopupPosition(400, 100);
					popPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
					hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

					popUp.show();
					yesBtn.addClickListener(new ClickListener() {
						public void onClick(final Widget sender) {
							Main.getLocal().setItem("SaveFile" + size,
									textBox.getText());

							size++;
							Main.getLocal().setItem("Save Size", "" + size);
							// indicates that file is saved.
							Main.getLocal().setItem("Save", "Yes");
							//play file saved sound
							MHCSound.playFileSaved();
							saveToMem(textBox.getText());
							// add it to the list box
							listBox.addItem(textBox.getText());
							// clear text box
							textBox.setText("");
							popUp.hide();
						}
					});
					noBtn.addClickHandler(new ClickHandler() {
						public void onClick(final ClickEvent event) {
							popUp.hide();
						}
					});
				} else if (textBox.getText().length() == 0
						&& listBox.getItemCount() > 0 && isFileSelected()) {
					// ask user first before updating
					final DialogBox popUp = new DialogBox(false);
					final VerticalPanel popPanel = new VerticalPanel();
					final HorizontalPanel hPanel = new HorizontalPanel();
					final Button noBtn = new Button("no");
					noBtn.setWidth("50px");
					final Button yesBtn = new Button("yes");
					yesBtn.setWidth("50px");
					popPanel.add(new HTML("<center>Overwrite file?</center>"));
					popPanel.add(hPanel);
					popUp.setWidget(popPanel);
					hPanel.add(yesBtn);
					hPanel.add(noBtn);
					popUp.setPopupPosition(400, 100);
					popPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
					hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

					popUp.show();
					yesBtn.addClickListener(new ClickListener() {

						public void onClick(final Widget sender) {
							for (int j = 0; j < size; j++) {
								if (Main.getLocal()
										.getItem("SaveFile" + j)
										.equals(listBox.getItemText(listBox
												.getSelectedIndex()))) {
									saveToMem(Main.getLocal().getItem(
											"SaveFile" + j));
									// exits once done
									j = size;
								}
							}
							MHCSound.playFileOverwritten();
							popUp.hide();
						}
					});
					noBtn.addClickHandler(new ClickHandler() {
						public void onClick(final ClickEvent event) {
							popUp.hide();
						}
					});
				} else {
					Window.alert("Please enter in a new save file name");
				}

			}

		});
		btnLoadFile.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(final ClickEvent event) {
				// check if list box has files
				// and load the selected file

				if (listBox.getItemCount() > 0
						&& Main.getLocal().getItem("Save") != null) {
					// checks if an item is selected
					if (isFileSelected()) {
						final DialogBox popUp = new DialogBox(false);
						final VerticalPanel popPanel = new VerticalPanel();
						final HorizontalPanel hPanel = new HorizontalPanel();
						final Button noBtn = new Button("no");
						noBtn.setWidth("50px");
						final Button yesBtn = new Button("yes");
						yesBtn.setWidth("50px");
						popPanel.add(new HTML(
								"<center>Load this file?</center>"));
						popPanel.add(hPanel);
						popUp.setWidget(popPanel);
						hPanel.add(yesBtn);
						hPanel.add(noBtn);
						popUp.setPopupPosition(400, 100);
						popPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
						hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						popUp.show();
						yesBtn.addClickListener(new ClickListener() {

							@Override
							public void onClick(final Widget sender) {
								//play load file sound
								MHCSound.playFileLoaded();
								loadFromMem(listBox.getItemText(listBox
										.getSelectedIndex()));
								popUp.hide();
							}
						});
						noBtn.addClickHandler(new ClickHandler() {
							public void onClick(final ClickEvent event) {
								popUp.hide();
							}
						});
						// end if selected
					} else {
						Window.alert("No file is selected!");  
						}
				} else {
					Window.alert("No files to load!");  
					}
			}
		});
		btnDeleteFile.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(final ClickEvent event) {
				if (listBox.getItemCount() > 0) {
					// ask user first before updating
					if (isFileSelected()) {
						final DialogBox popUp = new DialogBox(false);
						final VerticalPanel popPanel = new VerticalPanel();
						final HorizontalPanel hPanel = new HorizontalPanel();
						final Button noBtn = new Button("no");
						noBtn.setWidth("50px");
						final Button yesBtn = new Button("yes");
						yesBtn.setWidth("50px");
						popPanel.add(new HTML(
								"<center>Delete this file?</center>"));
						popPanel.add(hPanel);
						popUp.setWidget(popPanel);
						hPanel.add(yesBtn);
						hPanel.add(noBtn);
						popUp.setPopupPosition(400, 100);
						popPanel.setHorizontalAlign(HorizontalAlignment.CENTER);
						hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
						popUp.show();
						yesBtn.addClickListener(new ClickListener() {

							@Override
							public void onClick(final Widget sender) {
								for (int i = 0; i < size; i++) {
									if (Main.getLocal().getItem("SaveFile" + i) != null && 
									    Main.getLocal().getItem("SaveFile" + i).equals(listBox.getItemText(listBox.getSelectedIndex())))
									{

										// remove the data associated with the
										// save filed
										// text="Removing Save File \""+listBox.
										// getItemText(listBox.getSelectedIndex())+"\"\n\n";
										for (int l = 0; l < ModuleList.getMlist().size(); l++) {
											int size = Integer.parseInt(Main.getLocal()
													.getItem(listBox.getItemText(listBox.getSelectedIndex()) + "Module"	+ l));
											for (int k = 0; k < size; k++) { 
												String fileName = listBox.getItemText(listBox.getSelectedIndex());
												// save the module type
												Main.getLocal().removeItem(fileName + "Module Type:" + l + " " + k);
												Main.getLocal().removeItem(fileName + "Module Code Number:" + l	+ " " + k);
												Main.getLocal().removeItem(fileName + "Module X Posistion:"	+ l	+ " " + k);
												Main.getLocal().removeItem(fileName + "Module Y Posistion:"	+ l	+ " " + k);
												Main.getLocal().removeItem(fileName	+ "Module Status:" + l + " " + k);
												Main.getLocal().removeItem(fileName + "Module Orientation:"	+ l	+ " " + k);
											}
											//play file deleted sound
											MHCSound.playFileDeleted();
											Main.getLocal().removeItem(listBox.getItemText(listBox.getSelectedIndex()) + "Module" + l);
										}
										
										// remove from memory
										Main.getLocal().removeItem("SaveFile" + i);
										// remove from list box
										listBox.removeItem(listBox.getSelectedIndex());
										i = size;
										// exits loop after finishes
									}
								}
								popUp.hide();
							}
						});
						noBtn.addClickHandler(new ClickHandler() {
							public void onClick(final ClickEvent event) {
								popUp.hide();
							}
						});
				} // end if
					else {
						Window.alert("No file is selected");
					}
				} else {
					Window.alert("No files to delete");
				}
			}

		});
	}

	/**
	 * loadFromMem() method.
	 * 
	 * @function
	 * 
	 * @param fileName
	 * 
	 */
	public static void loadFromMem(final String fileName) {
		// clear the tables
		for (int i = 0; i <= ModuleList.getMlist().size(); i++) {
			LoggingModuleGUI.modulesFlexTableAll[i].removeAllRows();
			LoggingModuleGUI.modulesFlexTableAll[i].setHTML(0, 0,
					"<center><font size=\"1\">Code Number</font></center>");
			LoggingModuleGUI.modulesFlexTableAll[i].setHTML(0, 1,
					"<center><font size=\"1\">Position</font></center>");
			LoggingModuleGUI.modulesFlexTableAll[i].setHTML(0, 2,
					"<center><font size=\"1\">Status</font></center>");
			LoggingModuleGUI.modulesFlexTableAll[i].setHTML(0, 3,
					"<center><font size=\"1\">Orientation</font></center>");
			LoggingModuleGUI.modulesFlexTableAll[i].setHTML(0, 4,
					"<font size=\"1\">Delete</font>");
		}
		// Reset histogram
		LoggingModuleGUI.initHistogram();
		// load save
		for (int i = 0; i < ModuleList.getMlist().size(); i++) {
			// clears whatever is in the list
			ModuleList.getMlist().get(i).clear();

			int mSize = Integer.parseInt(Main.getLocal()
					.getItem(fileName + "Module" + i).trim());
			for (int j = 0; j < mSize; j++) {

				int number = Integer.parseInt(Main.getLocal().getItem(
						fileName + "ModuleType" + i + "" + j));
				ModuleType mType = Module.checkModuleType(number);
				Module m = new Module();
				m.setUrl(Module.getModuleImage(number));
				m.setModuleType(mType);
				//m.setUrl(Module.getModuleImage(mType.ordinal()));
				m.setCodeNumber(Integer.parseInt(Main.getLocal().getItem(
						fileName + "ModuleCode" + i + "" + j)));

				m.setPositionX(Integer.parseInt(Main.getLocal().getItem(
						fileName + "ModulePosX" + i + "" + j)));

				m.setPositionY(Integer.parseInt(Main.getLocal().getItem(
						fileName + "ModulePosY" + i + "" + j)));

				m.setStats(Main.getLocal().getItem(
						fileName + "ModuleStat" + i + "" + j));

				m.setOrientation(Integer.parseInt(Main.getLocal().getItem(
						fileName + "ModuleOrient" + i + "" + j)));
				ModuleList.getMlist().get(i).add(m); // adds to the list
				// update data
				LoggingModuleGUI.TableInit(m);
			}
		}
		// update label
		LoggingModuleGUI.totalM.setHTML("Total Module(s):"
				+ (ModuleList.getTotalModules())
				+ "&nbsp&nbsp&nbsp&nbsp usable:"
				+ ModuleList.getTotalUsableCount()
				+ "&nbsp&nbsp&nbsp&nbsp usable After Repair:"
				+ ModuleList.getTotalUsableAfterRepairCount()
				+ "&nbsp&nbsp&nbsp&nbsp Beyond Repair:"
				+ ModuleList.getTotalBeyondRepairCount());

		// initialize map
		MapGUI.initMap();
		//initialize confgui map
		ConfigurationGUI.redraw(0);
		ConfigurationGUI.redraw(1);
		ConfigurationGUI.setPlaceBtn(false);
		ConfigurationGUI.clearConfigMapList();
		ConfigurationGUI.showAllChanges();
	}

	/**
	 * saveToMem(final String fileName) method.
	 * 
	 * @param fileName
	 */
	public static void saveToMem(final String fileName) {
		for (int i = 0; i < ModuleList.getMlist().size(); i++) {
			// save size
			Main.getLocal().setItem(fileName + "Module" + i,
					"" + ModuleList.getMlist().get(i).size());
			for (int j = 0; j < ModuleList.getMlist().get(i).size(); j++) {

				// save the module type
				Main.getLocal().setItem(
						fileName + "ModuleType" + i + "" + j,
						""
								+ ModuleList.getMlist().get(i).get(j).getModuleType()
										.ordinal());

				// save the code number
				Main.getLocal().setItem(fileName + "ModuleCode" + i + "" + j,
						"" + ModuleList.getMlist().get(i).get(j).getCodeNumber());

				// save the position x
				Main.getLocal().setItem(fileName + "ModulePosX" + i + "" + j,
						"" + ModuleList.getMlist().get(i).get(j).getPositionX());

				// save the position y
				Main.getLocal().setItem(fileName + "ModulePosY" + i + "" + j,
						"" + ModuleList.getMlist().get(i).get(j).getPositionY());

				// save the Status
				Main.getLocal().setItem(fileName + "ModuleStat" + i + "" + j,
						ModuleList.getMlist().get(i).get(j).getStats());

				// save the orientation
				Main.getLocal().setItem(fileName + "ModuleOrient" + i + "" + j,
						"" + ModuleList.getMlist().get(i).get(j).getOrientation());
			}
		}

	}

	/**
	 * isFileSelected() method.
	 * 
	 * @function
	 * @return boolean
	 * 
	 */
	private boolean isFileSelected() {
		for (int i = 0; i < listBox.getItemCount(); i++) {
			if (listBox.isItemSelected(i)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * getGUI() method.
	 * 
	 * @return verticalPanel
	 */
	public final com.google.gwt.user.client.ui.VerticalPanel getGUI() {
		return verticalPanel;
	}
}